var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var app = getApp();

Page({
  data: {
    cartGoods: [],
    checkedGoodsAmount: 0.0,
    cartTotal: {},
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    remindValue: ['', '', '送'],
    plusFlag: ['', ' ', '  '],
    hasLogin: false,
    invalidWord: '宝贝已失效，编辑删除哦'
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function() {
    // 页面渲染完成
  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getCartList();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onShow: function() {
    // 页面显示
    if (app.globalData.hasLogin) {
      this.getCartList();
    }

    this.setData({
      hasLogin: app.globalData.hasLogin,
      isEditCart: false
    });

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  getCartList: function() {
    let that = this;

    let checkedGoodsAmount = 0;
    let checkedGoodsCount = 0;
    let checkedIntergral = 0;
    let goodsAmount = 0;
    let goodsCount = 0;
    let intergral = 0;
    let ircheckedGoodsAmount = 0;
    let ircheckedIntergral = 0;
    let irgoodsAmount = 0;
    let irintergral = 0;

    let cartLists = wx.getStorageSync('cart');
    let cartList = []
    if (cartLists.length > 0) {
      let productIds = '';
      for (let i = 0; i < cartLists.length; i++) {
        productIds += cartLists[i].productId + ","
      }
      productIds = productIds.substring(0, productIds.length - 1);
      util.request(api.CartCheck, {
        productIds: productIds
      }).then(function(res) {
        let returnProdects = res.data.products
        for (let u = 0; u < cartLists.length; u++) {
          let name = cartLists[u].goodsName
          if (name.length > 22) {
            name = name.substring(0, 22) + '...';
          }
          cartLists[u].goodsName = name
          for (let j = 0; j < returnProdects.length; j++) {
            if (cartLists[u].productId == returnProdects[j].id) {
              cartLists[u].deleted = returnProdects[j].deleted;

              if (cartLists[u].deleted) {
                cartLists[u].isTouchRemove = false
                cartLists[u].checked = false
              } else {
                cartList.push(cartLists[u])
              }
            }
          }
        }
        // 后台删除的商品从缓存中去除
        wx.setStorageSync('cart', cartList);
        // 计算总价格
        for (let i = 0; i < cartList.length; i++) {
          if (!cartList[i].deleted) {
            cartList[i].checked = that.data.checkedAllStatus
            if (cartList[i].checked) {
              checkedIntergral += cartList[i].integral * cartList[i].number
              checkedGoodsCount += cartList[i].number
              goodsAmount += cartList[i].retailPrice
              if (cartList[i].priceFlag != 2) {
                checkedGoodsAmount += cartList[i].retailPrice * cartList[i].number
              }
              goodsCount += cartList[i].number
              intergral += cartList[i].integral
            }
            if (!cartList[i].checked) {
              ircheckedGoodsAmount += cartList[i].number
              irgoodsAmount += cartList[i].retailPrice
              ircheckedIntergral += cartList[i].integral
              irintergral += cartList[i].integral
            }
          }
        }
        //  wx.setStorageSync('cart', cartList);

        var cartTotal = {
          checkedGoodsAmount: checkedGoodsAmount,
          checkedGoodsCount: checkedGoodsCount,
          checkedIntergral: checkedIntergral,
          goodsAmount: goodsAmount,
          goodsCount: goodsCount,
          intergral: intergral,
          ircheckedGoodsAmount: ircheckedGoodsAmount,
          ircheckedIntergral: ircheckedIntergral,
          irgoodsAmount: irgoodsAmount,
          irintergral: irintergral
        }
        if (cartList.length >= 0) {
          that.setData({
            cartGoods: cartList,
            cartTotal: cartTotal,
            checkedGoodsAmount: checkedGoodsAmount
          });
          if (cartList.length != 0) {
            that.setData({
              checkedAllStatus: that.isCheckedAll()
            });
          }
        }
      })
    } else {
      var cartTotal = {
        checkedGoodsAmount: 0,
        checkedGoodsCount: 0,
        checkedIntergral: 0,
        goodsAmount: 0,
        goodsCount: 0,
        intergral: 0,
        ircheckedGoodsAmount: 0,
        ircheckedIntergral: 0,
        irgoodsAmount: 0,
        irintergral: 0
      }
      that.setData({
        cartGoods: [],
        cartTotal: cartTotal,
        checkedGoodsAmount: 0
      });
    }
  },
  isCheckedAll: function() {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function() {
    let checkedAll = this.isCheckedAll()
    this.setData({
      checkedAllStatus: this.isCheckedAll()
    });
  },
  checkedItem: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;

    let goodids = that.data.cartGoods[itemIndex].id
    if (!this.data.isEditCart) {

      let checkedGoodsAmount = 0;
      let checkedGoodsCount = 0;
      let checkedIntergral = 0;
      let goodsAmount = 0;
      let goodsCount = 0;
      let intergral = 0;
      let ircheckedGoodsAmount = 0;
      let ircheckedIntergral = 0;
      let irgoodsAmount = 0;
      let irintergral = 0;

      let cartList = wx.getStorageSync('cart');

      for (let i = 0; i < cartList.length; i++) {
        if (!cartList[i].deleted) {
          if (itemIndex == i) {
            if (cartList[i].checked == true) {
              var Status = false
            }
            if (cartList[i].checked == false) {
              var Status = true
            }
            cartList[i].checked = Status
          }


          if (cartList[i].checked == true) {
            checkedIntergral += cartList[i].integral * cartList[i].number
            checkedGoodsCount += cartList[i].number
            goodsAmount += cartList[i].retailPrice
            if (cartList[i].priceFlag != 2) {

              checkedGoodsAmount += cartList[i].retailPrice * cartList[i].number
            }

            goodsCount += cartList[i].number
            intergral += cartList[i].integral
          }
          if (cartList[i].checked == false) {
            ircheckedGoodsAmount += cartList[i].number
            irgoodsAmount += cartList[i].retailPrice
            ircheckedIntergral += cartList[i].integral
            irintergral += cartList[i].integral
          }
        }
      }
      wx.setStorageSync('cart', cartList)
      var cartTotal = {
        checkedGoodsAmount: checkedGoodsAmount,
        checkedGoodsCount: checkedGoodsCount,
        checkedIntergral: checkedIntergral,
        goodsAmount: goodsAmount,
        goodsCount: goodsCount,
        intergral: intergral,
        ircheckedGoodsAmount: ircheckedGoodsAmount,
        ircheckedIntergral: ircheckedIntergral,
        irgoodsAmount: irgoodsAmount,
        irintergral: irintergral
      }


      // if (cartList.length != 0) {
      that.setData({
        cartGoods: cartList,
        cartTotal: cartTotal
      });
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });

    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function(element, index, array) {
        if (index == itemIndex) {
          element.checked = !element.checked;
        }

        return element;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  getCheckedGoodsCount: function() {
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function(v) {
      if (v.checked === true) {
        checkedGoodsCount += v.number;
      }
    });
    return checkedGoodsCount;
  },
  checkedAll: function() {
    let that = this;

    if (!this.data.isEditCart) {
      var productIds = this.data.cartGoods.map(function(v) {
        return v.productId;
      });

      let checkedGoodsAmount = 0;
      let checkedGoodsCount = 0;
      let checkedIntergral = 0;
      let goodsAmount = 0;
      let goodsCount = 0;
      let intergral = 0;
      let ircheckedGoodsAmount = 0;
      let ircheckedIntergral = 0;
      let irgoodsAmount = 0;
      let irintergral = 0;

      let cartList = wx.getStorageSync('cart');



      for (let i = 0; i < cartList.length; i++) {
        if (this.data.checkedAllStatus == true) {
          var Status = false
        }
        if (this.data.checkedAllStatus == false) {
          var Status = true
        }
        if (!cartList[i].deleted) {
          cartList[i].checked = Status
          if (cartList[i].checked) {
            checkedIntergral += cartList[i].integral * cartList[i].number
            checkedGoodsCount += cartList[i].number
            goodsAmount += cartList[i].retailPrice
            if (cartList[i].priceFlag != 2) {

              checkedGoodsAmount += cartList[i].retailPrice * cartList[i].number
            }
            goodsCount += cartList[i].number
            intergral += cartList[i].integral
          }
          if (cartList[i].checked == false) {
            ircheckedGoodsAmount += cartList[i].number
            irgoodsAmount += cartList[i].retailPrice
            ircheckedIntergral += cartList[i].integral
            irintergral += cartList[i].integral
          }
        }
      }
      wx.setStorageSync('cart', cartList)

      var cartTotal = {
        checkedGoodsAmount: checkedGoodsAmount,
        checkedGoodsCount: checkedGoodsCount,
        checkedIntergral: checkedIntergral,
        goodsAmount: goodsAmount,
        goodsCount: goodsCount,
        intergral: intergral,
        ircheckedGoodsAmount: ircheckedGoodsAmount,
        ircheckedIntergral: ircheckedIntergral,
        irgoodsAmount: irgoodsAmount,
        irintergral: irintergral
      }

      // if (cartList.length != 0) {
      that.setData({
        cartGoods: cartList,
        cartTotal: cartTotal
      });
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
      // }



    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function(v) {
        v.checked = !checkedAllStatus;
        return v;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  editCart: function() {
    var that = this;
    if (this.data.isEditCart) {
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
      this.checkedAll()
    } else {
      //编辑状态

      let tmpCartList = this.data.cartGoods.map(function(v) {
        v.checked = false;
        if (v.deleted) {
          v.checked = true;
          v.isTouchRemove = true;
        }
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }

  },
  updateCart: function(productId, goodsId, number, id) {
    let that = this;
    let cartList = wx.getStorageSync('cart');

    for (let i = 0; i < cartList.length; i++) {
      if (id == cartList[i].id & productId == cartList[i].productId) {
        cartList[i].number = number;
      }

    }
    wx.setStorageSync('cart', cartList)


  },
  cutNumber: function(event) {

    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
  },
  addNumber: function(event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);

  },
  checkoutOrder: function() {
    //获取已选择的商品
    let that = this;
    this.setData({
      disabled: !this.data.disabled,
      color: '',
      dis: false,
    });

    wx.setStorageSync('cartflag', 2);

    var checkedGoods = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true && element.deleted == false) {
        return true;
      } else {
        return false;
      }
    });

    if (checkedGoods.length <= 0) {
      return false;
    }

    // // storage中设置了cartId，则是购物车购买
    try {
      wx.setStorageSync('cartId', 0);
      wx.setStorageSync('cartGoods', that.data.cartGoods);
      wx.navigateTo({
        url: '../checkout/checkout'
      })
    } catch (e) {}

  },

  deleteCart: function(e) {
    //获取已选择的商品
    let that = this;

    let ids = this.data.cartGoods.filter(function(element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (ids.length <= 0) {
      return false;
    }


    var arr = wx.getStorageSync('cart')
    var listCart = [];
    if (arr.length == ids.length) {
      wx.setStorageSync('cart', listCart);
      // this.onShow();
      var cartTotal = {
        checkedGoodsAmount: 0,
        checkedGoodsCount: 0,
        checkedIntergral: 0,
        goodsAmount: 0,
        goodsCount: 0,
        intergral: 0,
        ircheckedGoodsAmount: 0,
        ircheckedIntergral: 0,
        irgoodsAmount: 0,
        irintergral: 0
      }
        that.setData({
          cartGoods: [],
          cartTotal: cartTotal,
          checkedGoodsAmount: 0
        });
    } else {
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < ids.length; j++) {
          if (arr[i].id == ids[j].id && arr[i].productId == ids[j].productId) {
            arr[i].deleteCarts = 1;
          }
        }
        if (arr[i].deleteCarts != 1) {
          listCart.push(arr[i]);
        }
      }
      wx.setStorageSync('cart', listCart);
      this.onShow();
    }
  }
})